<template>
    <div class="order-apply-invoice">
      <div ref="chartContainer" id="bar2Main" style="width: 100%; height: 400px;"></div>
    </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, watch, onBeforeUnmount, nextTick } from 'vue'
import * as echarts from 'echarts'
import { name } from 'echarts-extension-amap'
const props = defineProps({
  config: {
    type: Object,
    default: ()  => ({
      xAxisData: [],
      yAxisData: []
    }),
  },
})

const chartContainer = ref<HTMLElement | null>(null)
let chartInstance: echarts.ECharts | null = null
const initChart = ()=> {
  if (!chartContainer.value) return
  
  // 销毁旧实例（避免内存泄漏）
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  
  // 创建新实例
  chartInstance = echarts.init(chartContainer.value)
  updateChart()
}

// 更新图表数据
const updateChart = () => {
  if (!chartInstance) return
  
  const option = {
    legend: {
      right: '50px',
      top: '20px',
      data: ['回调箱量']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: props.config.xAxisData
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: props.config.yAxisData,
      type: 'bar',
      name: '回调箱量',
      label: {
        show: true, // 显示标签
        position: 'top',
        formatter: '{c}个', // 显示数据值
      }
    }]
  }
  
  chartInstance.setOption(option)
  chartInstance.resize() // 确保图表正确渲染
}

watch(() => props.config,(newVal) =>{
  if (!chartInstance) {
    initChart()
  } else {
    updateChart()
  }
},{deep:true})
onMounted(() => { 
  nextTick(() => {
    initChart()
  })
})  
// 组件卸载时清理
onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})
</script>
<style lang="scss" scoped></style>